package com.eastsunsoft.swordfish.gateway.fallback;

import com.eastsunsoft.swordfish.common.ApiConstant;
import com.eastsunsoft.swordfish.common.ResJson;
import com.eastsunsoft.swordfish.common.ServiceConstant;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * <h1>OssFallbackProvider</h1>
 * </br>
 *
 * @author donny
 * @date 22/09/2017
 */
@Component
public class OssFallbackProvider implements ZuulFallbackProvider {
    private final ObjectMapper om;

    @Autowired
    public OssFallbackProvider(ObjectMapper om) {
        this.om = om;
    }

    @Override
    public String getRoute() {
        return ServiceConstant.OSS;
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }

            @Override
            public String getStatusText() throws IOException {
                return this.getStatusCode().getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                ResJson resJson = new ResJson();
                resJson.setErrcode(ApiConstant.ERRCODE_SERVICE_TEMPDOWN);
                resJson.setMsg(ApiConstant.ERRMSG_SERVICE_TEMPDOWN);
                return new ByteArrayInputStream(om.writeValueAsBytes(resJson));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);

                return httpHeaders;
            }
        };
    }
}
